<template>
	<view class="theme-index-bg">
		<u-navbar titleStyle="font-size:20px;font-weight:600" :leftIconSize='0' :placeholder='true'
			:bgColor="'rgb(215, 231, 253)'" title="首页"> </u-navbar>
		<view class="exam-content">
			<view class="flex-jc-s-b" style="color: #333333;position: relative;">
				<view class="">
					<text class="titleCouser">{{homeInfo.course.rootName||''}}</text>
					<text style="margin-left: 16px;font-size: 12px;">{{homeInfo.course.parentName||''}}</text>
				</view>
				<view class="white-bg flex-jc-s-b"
					style="color:#fff;width:60px;font-size: 10px;border-radius: 4px;flex-direction: column;padding-bottom: 3px;padding-bottom: 2px;position: absolute;right: 0;top: 0px;">
					<view class="width-100 text-center"
						style="border-radius: 4px 4px 7px 0px;background: linear-gradient(138deg, #6F9DFF 0%, #437EFC 100%);padding:4px;margin-bottom: 2px;">
						账号有效期</view>
					<view class="color-blue text-center" v-if="recordData">
						<text style="font-size: 18px;font-weight: bold;">{{recordData.timeDiffText}}</text>
						{{recordData.timeDiffUnit}}
					</view>
				</view>
			</view>
			<view class="flex-center nameTile" @click="changeCourseHandle">
        <view class="flex-al-center">
          <text class="titleCouser" style="margin-right: 8px">{{homeInfo.course.name||''}}</text>
          <u-icon v-if="genderList.length > 1" name="arrow-down" color="#333333" size="28"></u-icon>
        </view>
				<view class="title-line"></view>
			</view>
			<view class="white-bg margin-t-10px flex-center"
				style="border-radius:10px;flex-direction: column;padding: 25px 15px;">
				<view class="title-left width-100">自由练习</view>
				<view class="circle-bg">
					<view class="circle-theme" @click="fromSatrt('start')">
						<text style="font-weight:bold;">{{
							homeInfo.lastInfo.practise.answerAmount!=homeInfo.lastInfo.practise.questionAmount&&homeInfo.lastInfo.practise.answerAmount?
							'继续练习':'开始练习'
							}}</text>
						<text style="font-family:DIN;font-weight:bold;"
							v-if="homeInfo.lastInfo.practise.questionAmount==homeInfo.lastInfo.practise.answerAmount||!homeInfo.lastInfo.practise.answerAmount">
							{{homeInfo.lastInfo.practise.questionAmount||0}}题
						</text>
						<text style="font-family:DIN;font-weight:bold;" v-else>
							{{homeInfo.lastInfo.practise.answerAmount||0}}/{{homeInfo.lastInfo.practise.totalAmount||homeInfo.lastInfo.practise.questionAmount||0}}
						</text>
					</view>
				</view>
				<!-- 未答完题显示 -->
				<view v-if='homeInfo.lastInfo.practise.answerAmount!=homeInfo.lastInfo.practise.questionAmount'
					class="flex width-100" style="margin-top: 45px;font-weight: bold;font-size: 18px;">
					<view class="flex-column">
						<text
							style="font-family:DIN;">{{homeInfo.lastInfo.practise.totalAmount-homeInfo.lastInfo.practise.answerAmount||'-'}}</text>
						<text class="text-gray margin-t-5px">未做题</text>
					</view>
					<view class="flex-column"
						@click="gotoErrorPage()">
						<text
							style="font-family:DIN;color: #366DE8;">{{homeInfo.lastInfo.practise.errorAmount||'-'}}</text>
						<text class="text-gray nowrap margin-t-5px">错题（点击查看）</text>
					</view>
					<view class="flex-column">
						<text
							style="font-family:DIN;">{{homeInfo.lastInfo.practise.accuracy!=undefind?(homeInfo.lastInfo.practise.accuracy*100).toFixed():'-'}}{{homeInfo.lastInfo.practise.accuracy?'%':''}}</text>
						<text class="text-gray margin-t-5px">正确率</text>
					</view>
				</view>
				<!-- 答完题显示 -->
				<view v-if='homeInfo.lastInfo.practise.answerAmount==homeInfo.lastInfo.practise.questionAmount'
					class="flex width-100" style="margin-top: 45px;font-weight: bold;font-size: 18px;">
					<view class="flex-column">
						<text style="font-family:DIN">{{'-'}}</text>
						<text class="text-gray margin-t-5px">未做题</text>
					</view>
					<view class="flex-column">
						<text style="font-family:DIN;color: #366DE8;">{{'-'}}</text>
						<text class="text-gray nowrap margin-t-5px">错题（点击查看）</text>
					</view>
					<view class="flex-column">
						<text style="font-family:DIN">{{'-'}}</text>
						<text class="text-gray margin-t-5px">正确率</text>
					</view>
				</view>
				<!-- 	v-if='homeInfo.lastInfo.practise.answerAmount==homeInfo.lastInfo.practise.questionAmount' -->
				<view class="flex-jc-s-b width-100 cart-info" style="background: #F5F7FF"
					v-if='homeInfo.lastInfo.practise.answerAmount==homeInfo.lastInfo.practise.questionAmount'
					@click="gotoPage('pages/report/report', {id:homeInfo.lastInfo.practise.id, isHistory: true,mode:'practise',isBback:true})">
					<text class="text-title-icon" style="background-color:#366DE8 ;">上次练习</text>
					<text>做题数：{{homeInfo.lastInfo.practise.answerAmount||0}}</text>
					<text>正确率：{{homeInfo.lastInfo.practise.accuracy!=undefind?(homeInfo.lastInfo.practise.accuracy*100).toFixed():'-'}}{{homeInfo.lastInfo.practise.accuracy?'%':''}}</text>
					<text
						v-if="homeInfo.lastInfo.test.submitTime">{{homeInfo.lastInfo.test.submitTime.split(' ')[0].split('-')[1]+'月'+homeInfo.lastInfo.test.submitTime.split(' ')[0].split('-')[2]+'日'||''}}</text>
				</view>
				<!-- 答完题显示 end-->
				<view class="margin-t-40rpx width-100"
					v-if="homeInfo.lastInfo.practise.answerAmount&&homeInfo.lastInfo.practise.answerAmount!=homeInfo.lastInfo.practise.questionAmount">
					<u-button type="primary" @click="fromSatrt"
						:customStyle="{'font-weight':' bold','font-size':' 15px'}"
						color="linear-gradient(-90deg, #4F71FF 0%, #679CFF 100%)" shape="circle" text="从头开始"></u-button>
				</view>
			</view>
			<view class="white-bg  margin-t-40rpx" style="border-radius: 20rpx;padding: 25px 15px;">
				<view class="title-left-yellow">模拟考试</view>
				<view class="margin-t-40rpx">
					<u-button :customStyle="{'font-weight':' bold','font-size':' 15px'}" type="primary"
						color="linear-gradient(-90deg, #FF950C 0%, #FFB72B 100%)" shape="circle" text="模拟考试"
						@click="routePage('', '', '', false, 'test')"></u-button>
				</view>
				<view class="flex-jc-s-b cart-info" v-if="homeInfo.lastInfo.test.id"
					@click="gotoPage('pages/report/report', {id:homeInfo.lastInfo.test.id, isHistory: true,mode:'test',isBback:true})">
					<text class="text-title-icon">上次成绩</text>
					<text>{{homeInfo.lastInfo.test.mark||0}}分</text>
					<text
						v-if="homeInfo.lastInfo.test.submitTime">{{getTime(homeInfo.lastInfo.test.durationSecond,'m-s')}}</text>
					<text
						v-if="homeInfo.lastInfo.test.submitTime">{{homeInfo.lastInfo.test.submitTime.split(' ')[0].split('-')[1]+'月'+homeInfo.lastInfo.test.submitTime.split(' ')[0].split('-')[2]+'日'||''}}</text>
					<text class="yellow-text" v-if="homeInfo.lastInfo.test.mark< 60">建筑学徒</text>
					<text class="yellow-text" v-if="80>homeInfo.lastInfo.test.mark>= 60">预备梓人</text>
					<text class="yellow-text" v-if="90>homeInfo.lastInfo.test.mark>= 80">能工巧匠</text>
					<text class="yellow-text" v-if="homeInfo.lastInfo.test.mark>= 90">城市建造者</text>
				</view>
			</view>
			<!-- 选择模式 -->
			<u-popup @close="showPopup=false" :customStyle="{'border-radius': '4px'}" :show="showPopup" mode='center'>
				<view class="modePopup text-center ">
					<view style="height: 120px;line-height: 120px;text-align: center;">请选择练习模式</view>
					<view class="color-blue modePopupItem flex width-100">
						<view style="border-right: none;" @click="routePage('answer')">答题模式</view>
						<view @click="routePage('recive')">背题模式</view>
					</view>
				</view>
			</u-popup>
      <u-picker :show="showCoursePicker" ref="coursePicker" :columns="[data.firstColumns, data.secondColumns, data.thirdColumns]" title="请选择科目" keyName="name" itemHeight="60"
                @confirm="confirmChange" @change="changeHandler" :defaultIndex="data.selectedCourseIndex"
                @cancel="showCoursePicker = false" @close="showCoursePicker = false" :closeOnClickOverlay="true"></u-picker>
		</view>
	</view>

</template>

<script setup>
	import { onMounted, reactive, ref, getCurrentInstance, defineExpose } from 'vue'
  import { onLoad } from "@dcloudio/uni-app";
	import { modelInfo, trainLastInfo, courseInfo, studentDetail, trainBankInfo } from '@/api/tabBarPages/index.js'
	import { dateDiff, timeDiff } from '@/utils/timeStamp.js'
	import { getTime } from '@/utils/timeStamp.js'
	import pageRoute from '@/utils/pageRoute'
	import onShare from '@/utils/share.js';
  import {coursList, login, treeStudentCourse} from '../../api/login'
	const {onShareAppMessage,onShareTimeline} = onShare()
	const gotoPage = (url, params) => {
		pageRoute.route(url, params);
	}
	const { proxy } = getCurrentInstance()
  const showPopup = ref(false)
  const showCoursePicker = ref(false)
  const genderList = ref([])
  const data = reactive({
    courseTreeList:[],
    firstColumns: [],
    secondColumns: [],
    thirdColumns: [],
    selectedCourseIndex: [],
    selectedFirstIndex: 0,
    selectedSecondIndex: 0,
  })
  const initStudentCourse = (idCard) => {
    treeStudentCourse({idCard: idCard}).then((res) => {
      data.courseTreeList = res.rows
      data.firstColumns = data.courseTreeList
      data.secondColumns = data.courseTreeList[data.selectedFirstIndex].children
      data.thirdColumns = data.courseTreeList[data.selectedFirstIndex].children[data.selectedSecondIndex].children
    })
  }
  function changeHandler(e) {
    const {indexs} = e;
    courseChangeHandle(indexs)
  }
  function courseChangeHandle(indexs) {
    if(indexs[0] !== data.selectedCourseIndex[0]) {
      indexs[1] = 0
      indexs[2] = 0
    }
    data.selectedCourseIndex = indexs
    data.selectedFirstIndex = indexs[0]
    data.selectedSecondIndex = indexs[1]
    data.secondColumns = data.courseTreeList[data.selectedFirstIndex].children
    data.thirdColumns = data.courseTreeList[data.selectedFirstIndex].children[data.selectedSecondIndex].children
    let secondLevelList = []
    let thirdLevelList = []
    secondLevelList =[...data.secondColumns[data.selectedFirstIndex]]
    thirdLevelList = [...data.thirdColumns[data.selectedFirstIndex][data.selectedSecondIndex]]
    proxy.$refs.coursePicker.setColumnValues(1, secondLevelList)
    proxy.$refs.coursePicker.setColumnValues(2, thirdLevelList)
  }
	const fromSatrt = (type) => {
		// console.log(homeInfo.lastInfo.practise.answerAmount, 'homeInfo.lastInfo.practise.answerAmount')
		// console.log(homeInfo.lastInfo.practise.questionAmount, 'homeInfo.lastInfo.practise.questionAmount')
		if (type == 'start' && homeInfo.lastInfo.practise.answerAmount == homeInfo.lastInfo.practise.questionAmount) {
			showPopup.value = true;
			return
		}
		if (type == 'start' && homeInfo.lastInfo.practise.answerAmount != undefined && homeInfo.lastInfo.practise
			.answerAmount != homeInfo.lastInfo.practise.questionAmount) {
			routePage('practise', '', homeInfo.lastInfo.practise.id || '', true)
			return
		}
		showPopup.value = true
	}
	const routePage = (mode, path, id, isContinue, type, courseName) => {
		showPopup.value = false
		uni.$u.route({
			url: path || 'pages/paper/practice',
			params: {
				mode: mode || '',
				type: type || '',
				id: id || '',
				isStart: isContinue ? false : true,
				courseName: homeInfo.course.name || ''
			}
		})
	}
	const homeInfo = reactive({
		model: {},
		lastInfo: { practise: {}, test: {} },
		course: {},
	})
	const recordData = ref({

	})
  const changeCourseHandle = () => {
    if(genderList.value.length > 1) {
      showCoursePicker.value = true
    }
  }
  const confirmChange = (e) => {
    const {indexs, value} = e
    data.selectedCourseIndex = indexs
    uni.setStorageSync('selectedCourseIndex', data.selectedCourseIndex)
    homeInfo.course.rootName = value[0].name || ''
    homeInfo.course.parentName = value[1].name || ''
    homeInfo.course.name = value[2].name || ''
    homeInfo.course.courseId = value[2].id
    let idCard = uni.getStorageSync('idCard')
    let length = idCard.length
    let dataForm = {
      "idCard": idCard,
      "password": idCard.substring(length-6, length),
      "courseId": homeInfo.course.courseId,
      "code": "",
      "bingFlag": "0", //0正常登录 1绑定微信
      "openIdFlag": "0" //是否校验openid 标志;null或者1校验 /0不校验
    }
    login(dataForm, '').then((res) => {
      uni.setStorageSync('idCard',res.data.idCard)
      uni.setStorageSync('token', res.data.sessionKey)
      uni.setStorageSync('loginType', 'student')
      initTrainPage()
      initDetail()
      showCoursePicker.value = false
    })
  }
  const initCourse = (idCard) => {
    coursList({ idCard: idCard }).then((res) => {
      genderList.value = []
      if (res.data) {
        res.data.map((item) => {
          item.status == '2' ? genderList.value.push(item) : ''
        })
        // let index = genderList.value.findIndex((item) => item.courseId == homeInfo.course.id)
        // data.selectedCourseIndex = index != -1? index : 0
      }
      if (!res.data) { return }
    })
  }
	const initTrainPage = () => {
		courseInfo().then(res => { homeInfo.course = res.data || {} })
		modelInfo().then((res) => {})
		trainLastInfo('practise').then(lastRes => {
			homeInfo.lastInfo.practise = lastRes.data || {}
			console.log(homeInfo.lastInfo.practise.accuracy, '99')
			trainBankInfo().then((res) => {
				homeInfo.lastInfo.practise.questionAmount = res.data.questionAmount || ''
			})
		})
		trainLastInfo('test').then(lastRes => { homeInfo.lastInfo.test = lastRes.data || {} })
	}
	const initDetail = () => {
		studentDetail({}).then((res) => {
      initCourse(res.data.idCard)
      initStudentCourse(res.data.idCard)
			recordData.value = res.data || {}
			let hour = recordData.value.expiresHourAmount > 0 ? recordData.value.expiresHourAmount : 0;
			let datediff = parseInt(hour / 24);
			if (datediff == 0) {
				recordData.value.timeDiffText = hour
				recordData.value.timeDiffUnit = '小时'
			} else {
				recordData.value.timeDiffText = datediff
				recordData.value.timeDiffUnit = '天'
			}
		})
	}
	const gotoErrorPage = () => {
		let errorAmount = homeInfo.lastInfo.practise.errorAmount
		if (!errorAmount) {
			return
		}
		pageRoute.route('pages/paper/practice', {id:homeInfo.lastInfo.practise.id,onlyWrong:true,isHistory:true,mode:'practise',courseName: homeInfo.course.name|| ''})
	}
  defineExpose({
    initData: initData()
  });
  function initData() {
    let token = uni.getStorageSync('token')
    let idCard = uni.getStorageSync('idCard')
    if(token) {
      // initStudentCourse(idCard)
      initTrainPage()
      initDetail()
    }
  }
  onLoad((options) => {
    if(uni.getStorageSync('selectedCourseIndex')) {
      data.selectedCourseIndex = uni.getStorageSync('selectedCourseIndex')
    } else {
      data.selectedCourseIndex = [0,0,0]
    }
    // data.selectedCourseIndex = uni.getStorageSync('selectedCourseIndex') || [0,0,0]
    console.log(data.selectedCourseIndex, 'selectedCourseIndex')
  })
	onMounted(() => {
    // data.selectedCourseIndex = uni.getStorageSync('selectedCourseIndex')
    // console.log(data.selectedCourseIndex, 'selectedCourseIndex')

	})
</script>
<style lang="scss" scoped>
	.cart-info {
		position: relative;
		color: rgba(102, 102, 102, 0.7);
		height: 56px;
		font-size: .75rem;
		background: #FFFBF3;
		border-radius: 4px;
		margin-top: 15px;
		padding: 0 15px
	}

	.text-title-icon {
		position: absolute;
		top: 0;
		right: 0;
		display: block;
		width: 55px;
		text-align: center;
		height: 19px;
		line-height: 19px;
		font-size: 10px;
		font-family: PingFang SC;
		color: #FFFFFF;
		background: #FF9A11;
		border-radius: 2px;
	}

	.yellow-text {
		color: #FF9A11;
		// font-size: 17px;
		font-family: PingFang SC;
		// font-weight: bold;
	}

	.modePopup {
		width: calc(100vw - 52px);
		height: 130px;
		background: #FFFFFF;
		border-radius: 4px;

		// position: relative;
		.modePopupItem {
			position: absolute;
			width: 100%;
			bottom: 0;

			left: 0;

			view {
				height: 100%;
				width: 50%;
				height: 49px;
				line-height: 49px;
				border: 1px solid rgba(0, 0, 0, 0.1)
			}
		}
	}

	.nameTile {
		margin-top: 12px;
		flex-direction: column;
		width: fit-content;
	}

	.title-line {
		width: 25px;
		height: 3px;
		background: #366DE8;
		border-radius: 3px;
		margin: 9px 0 5px 0;

	}

	.titleCouser {
		font-size: 18px;
		font-weight: 800;
	}
</style>
